package com.iboran.guoyao_daxiang.util;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ByteArrayEntity;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.util.Map;

public class HttpRequestUtils {
   private static Logger logger = LoggerFactory.getLogger(HttpRequestUtils.class);    //日志记录
   public static void httpDown(String url,String input) {
		CloseableHttpClient httpclient = HttpClients.createDefault();
		HttpPost httppost = new HttpPost(url);
		RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(10000).setSocketTimeout(10000).build();
		httppost.setConfig(requestConfig);
		ByteArrayEntity entity = new ByteArrayEntity(input.getBytes(StandardCharsets.UTF_8));
		entity.setContentType("text/plain");
		httppost.setEntity(entity);
		CloseableHttpResponse response = null;
		try {
			response = httpclient.execute(httppost);
			int statusCode = response.getStatusLine().getStatusCode();
			if (statusCode != HttpStatus.SC_OK) {
				httppost.abort();
				throw new RuntimeException("HttpClient,error status code :" + statusCode);
			}
			HttpEntity responseEntity = response.getEntity();
			String result;
			if (responseEntity != null) {
				if (responseEntity.getContentType().getValue().contains("application/octet-stream")) {
					InputStream content = responseEntity.getContent();
					// 返回文件流
					File file = new File("testDownload.txt");
					FileOutputStream fileOutputStream = new FileOutputStream(file);
					int temp;
					while ((temp = content.read()) != -1) {
						fileOutputStream.write(temp);
					}
					fileOutputStream.close();
				} else {
					// 返回字符串
					result = EntityUtils.toString(responseEntity, "UTF-8");
					System.out.println(result);
				}
			}
			EntityUtils.consume(entity);
		} catch (ClientProtocolException e) {
			throw new RuntimeException("提交给服务器的请求，不符合 HTTP 协议", e);
		} catch (IOException e) {
			throw new RuntimeException("向服务器承保接口发起 http 请求,执行 post 请求异常", e);
		} finally {
			if (response != null) {
				try {
					response.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if (httpclient != null) {
				try {
					httpclient.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}

   /**
    * httpPost
    * @param url  路径
    * @param jsonParam 参数
    * @return
    */
   public static String httpPost(String url, JSONObject jsonParam){
       return httpPost(url, jsonParam, false);
   }

   /**
    * post请求
    * @param url         url地址
    * @param jsonParam     参数
    * @param noNeedResponse    不需要返回结果
    * @return
    */
   public static String httpPost(String url,JSONObject jsonParam, boolean noNeedResponse){
       //post请求返回结果
       DefaultHttpClient httpClient = new DefaultHttpClient();
       String str = "";
       HttpPost method = new HttpPost(url);
       try {
           if (null != jsonParam) {
               //解决中文乱码问题
               StringEntity entity = new StringEntity(jsonParam.toString(), "utf-8");
               entity.setContentEncoding("UTF-8");
               entity.setContentType("application/json");
               method.setEntity(entity);
           }
           HttpResponse result = httpClient.execute(method);
           url = URLDecoder.decode(url, "UTF-8");
           /**请求发送成功，并得到响应**/
           if (result.getStatusLine().getStatusCode() == 200) {
               
               try {
                   /**读取服务器返回过来的json字符串数据**/
                   str = EntityUtils.toString(result.getEntity());
                   if (noNeedResponse) {
                       return null;
                   }
//                   /**把json字符串转换成json对象**/
//                   jsonResult = JSONObject.fromObject(str);
               } catch (Exception e) {
                   return "请求失败"+e;
               }
           }
       } catch (IOException e) {
    	   return "请求失败"+e;
       }
       return str;
   }


   /**
	 * 发送get请求
	 * 
	 * @param url 路径
	 * @return
	 */
	public static String httpGet(String url) {
		// get请求返回结果
		String returnResult = null;
		try {
			DefaultHttpClient client = new DefaultHttpClient();
			// 发送get请求
			HttpGet request = new HttpGet(url);
			HttpResponse response = client.execute(request);
			/** 请求发送成功，并得到响应 **/
			if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
				/** 读取服务器返回过来的json字符串数据 **/
				returnResult = EntityUtils.toString(response.getEntity());
				logger.info("HttpRequestUtils.httpGet，returnResult = {}", returnResult);
				url = URLDecoder.decode(url, "UTF-8");
			} else {
				logger.error("get请求提交失败:" + url);
			}
		} catch (IOException e) {
			logger.error("get请求提交失败:" + url, e);
		}
		return returnResult;
	}
   
   /**
    * post请求
    * @param url 访问地址
    * @param clazz 返回值类型
    * @return
    */
   @SuppressWarnings("hiding")
	public static <T> T httpPost(String url, String input, Class<T> clazz,Map<String,String> heardMap) {
		// post请求返回结果
		DefaultHttpClient httpClient = new DefaultHttpClient();
		T jsonResult = null;
		HttpPost method = new HttpPost(url);
		if(heardMap!=null) {
			 for(String key:heardMap.keySet()) {
		      	   // 设置通用的请求属性
					 method.addHeader(key,heardMap.get(key));
		         }
				method.addHeader("Content-type","application/json; charset=utf-8");
		}

		try {
			if (null != input) {
				// 解决中文乱码问题
				StringEntity entity = new StringEntity(input, "utf-8");
				entity.setContentEncoding("UTF-8");
				entity.setContentType("application/json");
				method.setEntity(entity);
			}
			HttpResponse result = httpClient.execute(method);
			url = URLDecoder.decode(url, "UTF-8");
			/** 请求发送成功，并得到响应 **/
			if (result.getStatusLine().getStatusCode() == 200) {
				String str = "";
				try {
					/** 读取服务器返回过来的json字符串数据 **/
					str = EntityUtils.toString(result.getEntity());
					jsonResult = JSON.parseObject(str, clazz);
				} catch (Exception e) {
					logger.error("post请求提交失败:" + url, e);
				}
			}
		} catch (IOException e) {
			logger.error("post请求提交失败:" + url, e);
		}
		return jsonResult;
	}
   
   
   
   
   /**
    * 向指定 URL 发送POST方法的请求
    *
    * @param url
    *            发送请求的 URL
    * @param param
    *            请求参数，请求参数应该是 name1=value1&name2=value2 的形式。
    * @return 所代表远程资源的响应结果
    */
   public static String sendPost(String url, String param,Map<String,String> heardMap) {
       PrintWriter out = null;
       BufferedReader in = null;
       String result = "";
       try {
           URL realUrl = new URL(url);
           // 打开和URL之间的连接
           URLConnection conn = realUrl.openConnection();
           
           for(String key:heardMap.keySet()) {
        	   // 设置通用的请求属性
               conn.setRequestProperty(key, heardMap.get(key));
           }
           conn.setRequestProperty("Content-Type", "application/json;charset=utf-8");
           // 发送POST请求必须设置如下两行
           conn.setDoOutput(true);
           conn.setDoInput(true);
           // 获取URLConnection对象对应的输出流
           out = new PrintWriter(conn.getOutputStream());
           // 发送请求参数
           out.print(param);
           // flush输出流的缓冲
           out.flush();
           // 定义BufferedReader输入流来读取URL的响应
           in = new BufferedReader(
                   new InputStreamReader(conn.getInputStream()));
           String line;
           while ((line = in.readLine()) != null) {
               result += line;
           }
       } catch (Exception e) {
           System.out.println("发送 POST 请求出现异常！"+e);
           e.printStackTrace();
       }
       //使用finally块来关闭输出流、输入流
       finally{
           try{
               if(out!=null){
                   out.close();
               }
               if(in!=null){
                   in.close();
               }
           }
           catch(IOException ex){
               ex.printStackTrace();
           }
       }
       return result;
   }

   
   
   
}